package com.yaolifei.flower.model.utils;

import java.sql.Connection;
import java.util.List;

import org.nutz.dao.ConnCallback;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.impl.DaoSupport;
import org.nutz.dao.impl.entity.NutEntity;
import org.nutz.dao.impl.entity.field.NutMappingField;
import org.nutz.dao.jdbc.Jdbcs;

import com.yaolifei.flower.model.Model;
import com.yaolifei.flower.model.ModelColumn;

public class ModelEntityMaker {

	private DaoSupport support;

	public ModelEntityMaker(DaoSupport support) {
		this.support = support;
	}

	public Entity<Object> makeNutEntity(Model model) {
		final NutEntity<Object> en = new NutEntity<Object>(Object.class);
		en.setTableName(model.getPhysicalName());
		en.setViewName(model.getPhysicalName());

		List<ModelColumn> columns = model.getColumns();
		for (ModelColumn c : columns) {

			// 是实体字段
			NutMappingField ef = new NutMappingField(en);

			if (c.isAutoIncrease()) {
				ef.setAsAutoIncreasement();
				ef.setAsId();
			}
			if (!c.isNullable()) {
				ef.setAsNotNull();
			}
			ef.setName(c.getColumnName());

			ef.setType(c.getColumnType().getJavaClass());
			ef.setColumnName(c.getPhysicalName());

			// 猜测一下数据库类型
			Jdbcs.guessEntityFieldColumnType(ef);
			ef.setAdaptor(support.getJdbcExpert().getAdaptor(ef));

			en.addMappingField(ef);
		}
		en.checkCompositeFields(null);

		// 最后在数据库中验证一下实体各个字段
		support.run(new ConnCallback() {
			public void invoke(Connection conn) throws Exception {
				support.getJdbcExpert().setupEntityField(conn, en);
			}
		});

		// 搞定返回
		return en;
	}

}
